import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import VideoManager from '@/components/VideoManager'
import Login from '@/components/Login'
import Dashborad from '@/components/Dashborad'
import Home from '@/components/Home'

Vue.use(Router)

const vm = new Vue()

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '*',
      redirect: '/home'
    },
    {
      path: '/dashborad',
      name: 'Dashborad',
      component: Dashborad,
      children: [
        {
          path: '/videomanager',
          name: 'VideoManager',
          component: VideoManager
        },
        {
          path: '/home',
          name: 'Home',
          component: Home
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  console.log('beforeEach this:', this)
  console.log('from:', from)
  console.log('to:', to)
  if ('/' == from.path && !to.params.flag) {
    console.log('/')
    vm.$axios
      .get('/meiju-boss/api/v1/auth/user')
      .then(function(response) {
        console.log('response:', response)
        router.replace({
          name: 'Home',
          params: { user: response.data.data, flag: true }
        })
        next(false)
      })
      .catch(function(error) {
        console.log('error:', error)
        // router.replace('/login')
        router.push({ name: 'Login', params: { flag: true} })
        next(false)
      })
  } else {
    console.log('else')
    next(true)
  }
})

export default router
